//
//  UIView+HMBadge.m
//  Community
//
//  Created by haozy on 2019/9/3.
//  Copyright © 2019 bingqing. All rights reserved.
//

#import "UIView+HMBadge.h"
#import <objc/runtime.h>

static char badgeViewKey;
static NSInteger const pointWidth = 15; //小红点的宽高
static NSInteger const rightRange = 22; //距离控件右边的距离
static NSInteger const topRange = 0; //距离控件顶部的距离


@implementation UIView (HMBadge)

- (void)showBadgeWithNumber:(NSString *)magin
{
    if (self.badge == nil) {
        CGRect frame = CGRectMake(CGRectGetWidth(self.frame) + rightRange, topRange, pointWidth, pointWidth);
        self.badge = [UILabel createLabelFont:FONT_SIZE(9) color:[UIColor whiteColor] alignment:1];
        self.badge.backgroundColor = [UIColor colorWithHexString:@"ff5153"];
        
        self.badge.frame = frame;
        self.badge.layer.cornerRadius = pointWidth / 2;
        self.badge.layer.masksToBounds = YES;
    }
    self.badge.text = magin;
    
    if (magin.integerValue == 0) {
        [self hidenBadge];
    } else {
        if (magin.integerValue > 99) {
            self.badge.text = @"···";
        }
        [self addSubview:self.badge];
        [self bringSubviewToFront:self.badge];
    }
}

- (void)showBadgeWithNumber:(NSString *)magin andRightRange:(NSInteger)rightRange topRange:(NSInteger)topRange
{
    if (self.badge == nil) {
        CGRect frame = CGRectMake(CGRectGetWidth(self.frame) + rightRange, topRange, pointWidth, pointWidth);
        self.badge = [UILabel createLabelFont:FONT_SIZE(9) color:[UIColor whiteColor] alignment:1];
        self.badge.backgroundColor = [UIColor colorWithHexString:@"ff5153"];
        
        
        self.badge.frame = frame;
        self.badge.layer.cornerRadius = pointWidth / 2;
        self.badge.layer.masksToBounds = YES;
    }
    self.badge.text = magin;
    
    if (magin.integerValue == 0) {
        [self hidenBadge];
    } else {
        if (magin.integerValue > 99) {
            self.badge.text = @"···";
        }
        [self addSubview:self.badge];
        [self bringSubviewToFront:self.badge];
    }
}

- (void)hidenBadge
{
    //从父视图上面移除
    [self.badge removeFromSuperview];
}

#pragma mark - GetterAndSetter

- (UILabel *)badge
{
    //通过runtime创建一个UILabel的属性
    return objc_getAssociatedObject(self, &badgeViewKey);
}

- (void)setBadge:(UILabel *)badge
{
    objc_setAssociatedObject(self, &badgeViewKey, badge, OBJC_ASSOCIATION_RETAIN);
}

@end
